package cn.xing.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.xing.dao.LoginTicketDAO;
import cn.xing.dao.UserDAO;
import cn.xing.model.LoginTicket;
import cn.xing.model.User;
import cn.xing.util.NewsUtil;

@Service
public class UserService {
	private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	@Autowired
	private UserDAO userDAO;

	@Autowired
	private LoginTicketDAO loginTicketDAO;

	public Map<String, Object> register(String username, String password) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isBlank(username)) {
			map.put("msgname", "用户名不能为空");
			return map;
		}

		if (StringUtils.isBlank(password)) {
			map.put("msgpwd", "密码不能为空");
			return map;
		}

		User user = userDAO.selectByName(username);

		if (user != null) {
			map.put("msgname", "用户名已经被注册");
			return map;
		}

		// 密码
		user = new User();
		user.setName(username);
		user.setSalt(UUID.randomUUID().toString().substring(0, 5));
		String head = String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000));
		user.setHeadUrl(head);
		user.setPassword(NewsUtil.MD5(password + user.getSalt()));
		userDAO.addUser(user);

		// 设置登录状态
		String ticket = addLoginTicket(user.getId());
		map.put("ticket", ticket);
		return map;
	}

	public Map<String, Object> login(String username, String password) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isBlank(username)) {
			map.put("msgname", "用户名不能为空");
			return map;
		}

		if (StringUtils.isBlank(password)) {
			map.put("msgpwd", "密码不能为空");
			return map;
		}

		User user = userDAO.selectByName(username);

		if (user == null) {
			map.put("msgname", "用户名不存在");
			return map;
		}

		if (!NewsUtil.MD5(password + user.getSalt()).equals(user.getPassword())) {
			map.put("msgpwd", "密码不正确");
			return map;
		}

		map.put("userId", user.getId());

		String ticket = addLoginTicket(user.getId());
		map.put("ticket", ticket);
		return map;
	}

	private String addLoginTicket(int userId) {
		LoginTicket ticket = new LoginTicket();
		ticket.setUserId(userId);
		Date date = new Date();
		date.setTime(date.getTime() + 1000 * 3600 * 24);
		ticket.setExpired(date);
		ticket.setStatus(0);//0表示登录标志ticket有效
		ticket.setTicket(UUID.randomUUID().toString().replaceAll("-", ""));
		loginTicketDAO.addTicket(ticket);
		return ticket.getTicket();
	}

	public User getUser(int id) {
		return userDAO.selectById(id);
	}

	public void logout(String ticket) {
		loginTicketDAO.updateStatus(ticket, 1);
	}
}
